package com.imdroid.carac.net.weibo;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;

import com.imdroid.carac.IMDroid;
import com.imdroid.carac.R;
import com.imdroid.carac.net.weibo.util.Utility;

// 用来显示用户认证界面的dialog，封装了一个webview，通过redirect地址中的参数来获取accesstoken
public class WeiboDialog extends Dialog {

	private String mUrl;
	private WeiboAuthListener mListener;
	private ProgressDialog mSpinner;
	private WebView mWebView;

	public WeiboDialog(Context context, String url, WeiboAuthListener listener) {
		super(context,android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
		mUrl = url;
		mListener = listener;
	}

	@SuppressLint("SetJavaScriptEnabled")
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.weibo);

//		LinearLayout mContent = new LinearLayout(getContext());
//		addContentView(mContent, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

//		mWebView = new WebView(getContext());
		mWebView = (WebView) findViewById( R.id.web_view );
		mWebView.setVerticalScrollBarEnabled(false);
		mWebView.setHorizontalScrollBarEnabled(false);
		mWebView.getSettings().setJavaScriptEnabled(true);
		mWebView.setWebViewClient(new WeiboDialog.WeiboWebViewClient());
		mWebView.loadUrl(mUrl);
		mWebView.setVisibility(View.INVISIBLE);
        
//		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
//		lp.leftMargin = 80;
//		lp.rightMargin = 80;
//		mContent.addView(mWebView, lp );
		
		mSpinner = new ProgressDialog(getContext());
		mSpinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
		mSpinner.setMessage("Loading...");
		mSpinner.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				onBack();
				return false;
			}
		});
		
		((Button) findViewById( R.id.button_later )).setOnClickListener( new View.OnClickListener() { public void onClick(View v) {
			dismiss();
		} } );
		
		((Button) findViewById( R.id.button_never )).setOnClickListener( new View.OnClickListener() { public void onClick(View v) {
			IMDroid.setWeiboLoginRemind(false);
			dismiss();
		} } );
	}

	protected void onBack() {
		try {
			mSpinner.dismiss();
			if (null != mWebView) {
				mWebView.stopLoading();
				mWebView.destroy();
			}
		} catch (Exception e) {
		}
		dismiss();
	}
	
	
	
	
	private class WeiboWebViewClient extends WebViewClient {

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			 if (url.startsWith("sms:")) {  //针对webview里的短信注册流程，需要在此单独处理sms协议
	                Intent sendIntent = new Intent(Intent.ACTION_VIEW);  
	                sendIntent.putExtra("address", url.replace("sms:", ""));  
	                sendIntent.setType("vnd.android-dir/mms-sms");  
	                WeiboDialog.this.getContext().startActivity(sendIntent);  
	                return true;  
	            }  
			return super.shouldOverrideUrlLoading(view, url);
		}

		@Override
		public void onReceivedError(WebView view, int errorCode, String description,
				String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
			mListener.onError(new WeiboDialogError(description, errorCode, failingUrl));
			WeiboDialog.this.dismiss();
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			if (url.startsWith(com.imdroid.carac.net.Weibo.redirect)) { // 修改
				handleRedirectUrl(view, url);
				view.stopLoading();
				WeiboDialog.this.dismiss();
				return;
			}
			super.onPageStarted(view, url, favicon);
			mSpinner.show();
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			if (mSpinner.isShowing()) {
				mSpinner.dismiss();
			}
			mWebView.setVisibility(View.VISIBLE);
//			mWebView.zoomOut();
//			mWebView.scrollBy(100, 100);
		}

		public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
			handler.proceed();
		}

	}

	private void handleRedirectUrl(WebView view, String url) {
		Bundle values = Utility.parseUrl(url);

		String error = values.getString("error");
		String error_code = values.getString("error_code");

		if (error == null && error_code == null) {
			mListener.onComplete(values);
		} else if (error.equals("access_denied")) {
			// 用户或授权服务器拒绝授予数据访问权限
			mListener.onCancel();
		} else {
			if(error_code==null){
				mListener.onWeiboException(new WeiboException(error, 0));
			}
			else{
				mListener.onWeiboException(new WeiboException(error, Integer.parseInt(error_code)));
			}
			
		}
	}
	
}
